<?php

namespace App\Jobs;

use App\Exceptions\Arr;
use App\Models\Appoint;
use App\Models\AppointNum;
use App\Models\HospitalUserFamily;
use App\Models\Notice;
use App\Models\TempPushRecord;
use App\Wechat\MiniTemp;
use App\Wechat\Temp;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\Middleware\WithoutOverlapping;
use Illuminate\Contracts\Queue\ShouldBeUniqueUntilProcessing;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\Model;

class TempPush implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    protected $tempPushRecord;
    protected $content;
    public $tries = 0;
    public $timeout = 90; // 秒

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(TempPushRecord $tempPushRecord,Model $content)
    {
        $this->tempPushRecord = $tempPushRecord;
        $this->content = $content;
        $this->onQueue('temp_push');
        $this->onConnection('redis');
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {

        $tempPushRecord = $this->tempPushRecord;
        $content = $this->content;

        try {
            $temp = new MiniTemp($tempPushRecord);
            $temp->send($content);
            $tempPushRecord->response_status = 1;
            $tempPushRecord->save();
        }catch (\Exception $exception){
            $tempPushRecord->response_status = 2;
            $tempPushRecord->response_code = $exception->getCode();
            $tempPushRecord->save();
            $this->fail($exception->getMessage());
        }
    }
    /**
     * 获取作业的唯一 ID。
     */
    public function uniqueId(): string
    {
        return $this->tempPushRecord->id;
    }

    /**
     * 同一条数据同一时间只处理一次。
     *
     * @return array<int, object>
     */
    public function middleware(): array
    {
        return [(new WithoutOverlapping($this->tempPushRecord->id))->dontRelease()];
    }

}
